package com.autumn.security.configure;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.autumn.spring.boot.properties.AutumnAuthProperties;

/**
 * 
 * 安全缓存提供程序配置
 * 
 * @author 杨昌国 2018-12-13 12:09:29
 */
@Configuration
@EnableConfigurationProperties({ AutumnAuthProperties.class })
public class AutumnSecurityCacheProviderConfiguration {

	/**
	 * 
	 * @param authProperties 授权属性
	 * @return
	 */
	private RedisManager shiroRedisManager(AutumnAuthProperties authProperties) {
		RedisManager redisManager = new RedisManager();
		redisManager.setHost(authProperties.getRedis().getHost());
		redisManager.setPort(authProperties.getRedis().getPort());
		if (authProperties.getExpire() != null) {
			redisManager.setExpire(authProperties.getExpire());
		}
		redisManager.setTimeout(authProperties.getRedis().getTimeout());
		redisManager.setPassword(authProperties.getRedis().getPassword());
		return redisManager;
	}

	/**
	 * 缓存管理
	 * 
	 * @param authProperties
	 * @return
	 */
	@Bean
	@Primary
	@ConditionalOnMissingBean(CacheManager.class)
	public CacheManager shiroCacheManager(AutumnAuthProperties authProperties) {
		if (authProperties.isRedisCacheProvider()) {
			RedisCacheManager redisCacheManager = new RedisCacheManager();
			redisCacheManager.setKeyPrefix(authProperties.getCacheKeyPrefix());
			redisCacheManager.setRedisManager(shiroRedisManager(authProperties));
			return redisCacheManager;
		}
		MemoryConstrainedCacheManager memoryCacheManager = new MemoryConstrainedCacheManager();
		return memoryCacheManager;
	}

	/**
	 * 会话Dao
	 * 
	 * @param authProperties
	 * @return
	 */
	@Bean
	@Primary
	@ConditionalOnMissingBean(SessionDAO.class)
	public SessionDAO shiroSessionDAO(AutumnAuthProperties authProperties) {
		if (authProperties.isRedisCacheProvider()) {
			RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
			redisSessionDAO.setKeyPrefix(authProperties.getSessionKeyPrefix());
			redisSessionDAO.setRedisManager(this.shiroRedisManager(authProperties));
			return redisSessionDAO;
		}
		MemorySessionDAO memorySessionDAO = new MemorySessionDAO();
		return memorySessionDAO;
	}
}
